import * as Msal from 'msal'
import store from '../store'
import { setToken } from '../utils/auth'

const config = {
  auth: {
    clientId: 'd150bf3a-417b-4599-a235-83cbd61d15f0',
    redirectUri: 'http://localhost:9528/dashboard',
    authority: 'https://login.microsoftonline.com/qdlsai.org'
  },
  cache: {
    cacheLocation: 'localStorage',
    storeAuthStateInCookie: true
  },
  // graphEndpoint: 'https://qdlsai.org/HSElearning.WebAPI',
  graphScopes: {
    scopes: ['user.read']
  }
}

if (process.env.NODE_ENV === 'production') {
  config.auth.redirectUri = 'https://hsadmin.azurewebsites.net/'// dashboard
}

export default {
  msalApp: null,
  /**
   * @return {Promise}
   */
  initialize() {
    this.msalApp = new Msal.UserAgentApplication(config)
    this.msalApp.handleRedirectCallback(function(_error, _response) {

    })
    return new Promise((resolve, _reject) => {
      if (this.isAuthenticated()) {
        this.acquireToken().then(token => {
          setToken(token)
          store.dispatch('user/getUserInfoByUPN').then(res => {
          }).catch((_err) => {
          })
        })
        resolve()
      } else {
        // no user at all - go sign in.
        this.signIn()
      }
    })
  },
  signIn() {
    this.msalApp.loginRedirect(config.graphScopes)
  },
  signOut() {
    this.msalApp.logout()
  },
  isAuthenticated() {
    if (this.msalApp.getAccount()) { return true }
    return false
  },
  getUserProfile() {
    return this.msalApp.getAccount()
  },
  acquireToken2() {
    var tokenRequest = {
      scopes: ['https://qdlsai.org/HSElearning.WebAPI/user_impersonation']
    }
    // if the user is already logged in you can acquire a token
    if (this.msalApp.getAccount()) {
      return new Promise((resolve, reject) => {
        this.msalApp.acquireTokenSilent(tokenRequest)
          .then(response => {
          // get access token from response
            return resolve(response.accessToken)
          })
          .catch(err => {
          // could also check if err instance of InteractionRequiredAuthError if you can import the class.
            console.log(err)
            if (err.name === 'InteractionRequiredAuthError') {
              return this.msalApp.acquireTokenRedirect(tokenRequest)
                .then(response => {
                // get access token from response
                  return resolve(response.accessToken)
                })
                .catch(_err => {
                  console.log(_err)
                // handle error
                })
            }
          })
      })
    } else {
      // user is not logged in, you will need to log them in to acquire a token
      this.signIn()
    }
  },
  acquireToken() {
    var tokenRequest = {
      scopes: ['https://qdlsai.org/HSElearning.WebAPI/user_impersonation']
    }
    // if the user is already logged in you can acquire a token
    if (this.msalApp.getAccount()) {
      return this.msalApp.acquireTokenSilent(tokenRequest)
        .then(response => {
          // get access token from response
          return response.accessToken
        })
        .catch(err => {
          // could also check if err instance of InteractionRequiredAuthError if you can import the class.
          console.log(err)
          if (err.name === 'InteractionRequiredAuthError') {
            return this.msalApp.acquireTokenRedirect(tokenRequest)
              .then(response => {
                // get access token from response
                response.accessToken
              })
              .catch(_err => {
                console.log(_err)
                // handle error
              })
          }
        })
    } else {
      // user is not logged in, you will need to log them in to acquire a token
      this.signIn()
    }
  }
}

